<?php

include "../../Lt/Common/functions.php";

class RBAC {

    private $acl = null;
    private $_defaultRole = 'guest';

    public function __construct() {
        Vendor('Zend.Acl');
        $this->acl = new Zend_Acl();
        $this->LoadRole();
        $this->LoadResource();
        $this->LoadAllow();
    }

    /*
     * 加载角色
     */

    private function LoadRole() {
        $model = D('Role');
        $res = $model->select();
        foreach ($res as $row) {
            $this->acl->addRole(new Zend_Acl_Role($row['id'])); //管理员
        }
        $this->acl->addRole(new Zend_Acl_Role('admin')); //加载超级管理员
        $this->acl->addRole(new Zend_Acl_Role($this->_defaultRole)); //默认
    }

    /*
     * 加载资源
     */

    private function LoadResource() {
        $model = D('Resource');
        $aclSettings = $model->getResList();
        foreach ($aclSettings as $key => $arr) {
            $this->acl->add(new Zend_Acl_Resource($key));
            foreach ($arr as $value) {
                $this->acl->add(new Zend_Acl_Resource($value), $key);
            }
        }
    }

    private function LoadAllow() {
        $this->acl->allow('guest', 'Admin:public');
        if (isset($_SESSION['user_role'])) {
            $roleid = $_SESSION['user_role'];
        } else {
            $roleid = $this->_defaultRole;
        }
        $model = D('resource');
        $allows = $model->query('select a.* from '.C('DB_PREFIX').'resource  a,'.C('DB_PREFIX').'role_action  b where b.id_action = a.id and b.id_role = ' . $roleid);
        $r = array();
        foreach ($allows as $row) {
            $r[$row['group_name'] . ':' . $row['module_name']][] = $row['action_name'];
        }
        foreach ($r as $key => $val) {
            $this->acl->allow($roleid, $key, $val);
        }
        $this->acl->allow('admin'); //超级管理员
    }
    
     public function preDispatch(){
        if (isset($_SESSION['user_role'])) {
            $role = $_SESSION['user_role'];
        }else{
            $role=$this->_defaultRole;
        }
        if (!$this->acl->hasRole($role)){
            $role = $this->_defaultRole;
        }
        $group_name = 'Admin';
        $module_name = strtolower(MODULE_NAME);
        $action_name = strtolower(ACTION_NAME);
        $resource = $group_name.':'.$module_name;
        if (!$this->acl->has($resource)){
            $resource=null;
        }
        
        if (!$this->acl->isAllowed($role,$resource,$action_name)){
            
            redirect(U('Admin/Public/login'));
        }
    }

}

?>
